package cn.zk.question.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * handler
 *
 * ChannelInboundHandlerAdapter 是 ChannelInboundHandlerAdapter的子类
 */
public class TcpServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    // 每个客户端的handler是独立的
    private int count;
    /**
     * 读取消息
     *
     * @param ctx
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        byte[] buffer = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(buffer);
        // buffer转为字符串
        String message = new String(buffer, StandardCharsets.UTF_8);
        System.out.println("==>服务器收到数据:"+message);
        System.out.println("==>服务器收到的消息量:"+(++this.count));

        // 回送数据给客户端 随机ID
        ByteBuf send = Unpooled.copiedBuffer(UUID.randomUUID().toString() + " ", StandardCharsets.UTF_8);
        ctx.writeAndFlush(send);
    }
    /**
     * channel 活跃
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("==>["+channel.remoteAddress()+"]"+" 已经上线！");
    }

    /**
     * channel 不活跃
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("==>["+channel.remoteAddress()+"]"+" 已经下线！");
    }

    /**
     * 出现异常会触发该方法 -> 关闭channel
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭
        ctx.close();
    }

}
